package com.yyh.synctool.client.component;

import com.yyh.common.Common;
import com.yyh.synctool.client.job.TaskId;
import com.yyh.synctool.client.job.JobFactory;
import com.yyh.synctool.client.job.TaskInfo;
import com.yyh.synctool.client.tool.TaskKey;
import com.yyh.synctool.client.job.TriggerFactory;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 同步任务管理
 * @author xuan
 * @date 2021/12/6
 */
@Component
public class TaskManagement
{
    private SchedulerFactoryBean schedulerFactoryBean;
    private TaskHelper taskHelper;
    /** 数据信息 */
    Map<String, TaskInfo> tasks = new LinkedHashMap<>();

    @Autowired
    public TaskManagement(SchedulerFactoryBean schedulerFactoryBean, TaskHelper taskHelper) {
        this.schedulerFactoryBean = schedulerFactoryBean;
        this.taskHelper = taskHelper;
        init();
    }

    /** 初始化操作 */
    private void init() {
        // 添加数据信息集
        JobDataMap dataMap = new JobDataMap();
        dataMap.put("infos", this.tasks);
        dataMap.put("taskHelper", this.taskHelper);

        // 调度器
        Scheduler scheduler = schedulerFactoryBean.getScheduler();

        try {

            // 测试任务
            Trigger interval5Seconds = TriggerFactory.getInterval5Seconds();
            JobDetail testJob = JobFactory.getTestJob(dataMap);
            tasks.put(TaskId.TEST, new TaskInfo(TaskId.TEST, "测试任务", true));
            scheduler.scheduleJob(testJob, interval5Seconds);

        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        // 触发器
        Trigger interval5Minutes = TriggerFactory.getInterval5Minutes();
        Trigger interval30Minutes = TriggerFactory.getInterval30Minutes();

        // 库存任务
        JobDetail stockJob = JobFactory.getStockJob(dataMap);
        tasks.put(TaskId.STOCK, new TaskInfo(TaskId.STOCK, "库存任务", true));
        // 价格任务
        JobDetail priceJob = JobFactory.getPriceJob(dataMap);
        tasks.put(TaskId.PRICE, new TaskInfo(TaskId.PRICE, "价格任务", true));

        try {

            // 调度任务
            scheduler.scheduleJob(stockJob, interval5Minutes);  // 库存
            scheduler.scheduleJob(priceJob, interval30Minutes);  // 价格

        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    /** 展示所有任务信息 */
    public Collection<TaskInfo> showTasks() {
        return tasks.values();
    }

    /** 手动执行 */
    public boolean execute(String taskId) {
        JobKey jobKey = TaskKey.getJobKey(taskId);
        if (null == jobKey) {
            return false;
        }
        try {
            Scheduler scheduler = schedulerFactoryBean.getObject();
            TaskInfo taskInfo = tasks.get(taskId);
            String previous = taskInfo.getExecTime();
            // 触发一次
            scheduler.triggerJob(jobKey);
            while (taskInfo.getExecTime().equals(previous)) {
                // 任务执行完成后退出
            }
            if (taskInfo.isAvailable()) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            // 防止未知异常
            e.printStackTrace();
            return false;
        }
    }

    /** 开启/关闭任务 */
    public void switchTask(String taskId) {
        JobKey jobKey = TaskKey.getJobKey(taskId);
        TaskInfo taskInfo = tasks.get(taskId);
        if (null == jobKey || null == taskInfo) {
            return;
        }

        try {
            Scheduler scheduler = schedulerFactoryBean.getObject();
            if (taskInfo.isOpen()) {
                // 开启状态
                scheduler.pauseJob(jobKey);
                taskInfo.setOpen(false);
            } else {
                // 关闭状态
                scheduler.resumeJob(jobKey);
                taskInfo.setOpen(true);
            }
        } catch (Exception e) {
            // 防止未知异常
            e.printStackTrace();
        }
    }

    public void start() {
        schedulerFactoryBean.start();
    }

    public void stop() {
        schedulerFactoryBean.stop();
    }
}
